package view.server;

import java.util.ArrayList;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import model.game.Player;
import java.io.IOException;
import javax.swing.*;
import controller.Link;
import model.User;
import controller.link.Yell;
import model.Server;

public class Console extends javax.swing.JFrame {

    private Server sv;
    private ArrayList<Player> players;
    private DefaultListModel listModel;
    private ArrayList<PlayerPane> playerPanels = new ArrayList<PlayerPane>();

    /** Creates new form Console */
    public Console() {
        listModel = new DefaultListModel();
        initComponents();
        this.init();
        txtchat.setEditable(false);
        txtchat.setLineWrap(true);
        txtchat.setWrapStyleWord(true);
        jScrollPane1.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener(){
			public void adjustmentValueChanged(AdjustmentEvent e){
			txtchat.select(txtchat.getHeight()+10000,0);
        
                        }
        });
        btnSend.getRootPane().setDefaultButton(btnSend);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        popPlayer = new javax.swing.JPopupMenu();
        optSee = new javax.swing.JMenuItem();
        optKick = new javax.swing.JMenuItem();
        optWatch = new javax.swing.JMenuItem();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        txtinput = new javax.swing.JTextField();
        btnSend = new javax.swing.JButton();
        btnsair = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtchat = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        playerList = new javax.swing.JToolBar();

        optSee.setText("See");
        popPlayer.add(optSee);

        optKick.setText("Kick");
        optKick.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optKick(evt);
            }
        });
        popPlayer.add(optKick);

        optWatch.setText("Watch");
        popPlayer.add(optWatch);

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Server Console");
        setBackground(new java.awt.Color(102, 51, 0));
        setResizable(false);

        btnSend.setText("Send");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enviarPressed(evt);
            }
        });

        btnsair.setText("Exit");
        btnsair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitPressed(evt);
            }
        });

        txtchat.setColumns(20);
        txtchat.setRows(5);
        txtchat.setComponentPopupMenu(popPlayer);
        jScrollPane1.setViewportView(txtchat);

        jLabel1.setText("Versão 1.0");

        jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        playerList.setFloatable(false);
        playerList.setOrientation(javax.swing.SwingConstants.VERTICAL);
        jScrollPane2.setViewportView(playerList);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtinput)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 593, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnsair, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 385, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                        .addComponent(btnsair, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtinput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSend))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void enviarPressed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enviarPressed
        String str = txtinput.getText(); //Colocar o switch dentro de um metódo;
        String comp;
        comp = str.toLowerCase();
        try {
            if (comp.startsWith("/")) {
                if (comp.startsWith("/stop")) {
                    sv.stop();
                    this.outputText("Fechando o servidor\n");
                    System.exit(0);
                } else 
                    if (comp.startsWith("/kick")) {                  
                        kickPlayer(comp.substring(6));                                
                } else 
                    this.outputText("Comando Inválido");
            } else {
                Yell yell = new Yell("Server", str);
                sv.sendToAll((Link)yell);
                this.outputText("Server : " + str);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.exit(0);
        }
        txtinput.setText(""); 
    }//GEN-LAST:event_enviarPressed

    private void exitPressed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitPressed
        try{
        sv.stop();
        System.exit(0);
        } catch(Exception e){
            System.out.println("Erro ao encerrar o servidor: \n " + e.getMessage());
        }
    }//GEN-LAST:event_exitPressed

    private void optKick(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optKick
        //
    }//GEN-LAST:event_optKick

    public void init() {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Console.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Console.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Console.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Console.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        serverStart();
        players = new ArrayList<Player>();
        
    }

    public void setSv(Server sv) {
        try {
            sv.start();
        } catch (Exception e) {
            System.out.println("S03-Falha ao executar servidor");
            System.out.println(e.getMessage());
            return;
        }
    }

    private void serverStart() {
        try {
            sv = new Server(2525, this);
            setSv(sv);
        } catch (IOException e) {
            System.out.println("S01-Porta em uso ou bloqueada pelo firewall");
            return;
        } catch (Exception e) {
            System.out.println("S02-Falha ao criar servidor");
            return;
        }
    }

    public void outputText(String str) {
        if (txtchat.isVisible()){
            txtchat.append(str + "\n");
        }        
    }
   
    public void addUser(User u) {     
        PlayerPane plPanel;
        plPanel = new PlayerPane(u, sv);
        Dimension dms = new Dimension(playerList.getWidth(), 49);
        plPanel.setPreferredSize(dms);
        plPanel.setMaximumSize(dms);
        playerList.add(plPanel, BorderLayout.NORTH);
        plPanel.setVisible(true);
        playerPanels.add(plPanel);
        plPanel.updateUI();
        
    }

    public void removeUser(String name) {
      String aux = "";
        for (int i = 0;i<playerPanels.size();i++) { 
            PlayerPane plPane = playerPanels.get(i);
            if (plPane.getUserName().getName().equals(name)){
               plPane.removeAll();
               playerList.remove(plPane);
               playerPanels.remove(plPane);
               playerList.updateUI();
               break;
            }
        }
    }
    
    public void kickPlayer(String element){
                        if (!element.equals("")) {
                            sv.kickPlayer(element);
                        } else 
                            this.outputText("Digite um player para ser kikado. (/kick <username>)");
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSend;
    private javax.swing.JButton btnsair;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JMenuItem optKick;
    private javax.swing.JMenuItem optSee;
    private javax.swing.JMenuItem optWatch;
    private javax.swing.JToolBar playerList;
    private javax.swing.JPopupMenu popPlayer;
    private javax.swing.JTextArea txtchat;
    private javax.swing.JTextField txtinput;
    // End of variables declaration//GEN-END:variables
}
